<?php
/**
 * Created by PhpStorm.
 * User: kwibon
 * Date: 2019/5/7
 * Time: 12:29
 */

namespace app\admin\controller;

use think\Db;
use \think\Cookie;
use app\admin\model\Faq as faqModel;
use app\admin\model\Faqtitle as faqtitleModel;
use app\api\controller\KbxOther;
use app\api\controller\Common as CommonApi;
class Faq extends User
{

    //主页面
    public function index(){
        $post = $this->request->post();
        //分页bug处理
        $temp_page=request()->param('page');
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('postlist');
        }else{
            //把条件写入缓存
            Cookie::set('postlist',$post);
        }

        $where = [];
        $where['deleted'] = 0;
        $typeid = 1;
        if (isset($post['typeid']) and $post['typeid'] > 0) {
            $typeid = $post['typeid'];
        }else{
            $post['typeid'] = $typeid;
        }
        $where['typeid'] = $typeid;

        $query = db("faq")
            ->where($where)
            ->field("count(id) as counts,groupid")
            ->group("groupid")
            ->select(false);

        $info = [];
        $info_where = [];
        if($typeid==1){//产品
            if (isset($post['keywords']) and !empty($post['keywords'])) {
                $info_where['t.name'] = ['like', '%' . $post['keywords'] . '%'];
            }

            $info = db("product t")
                ->join("(".$query.") as q","t.id=q.groupid")
                ->where($info_where)
                ->field("t.id,t.name,q.counts")
                ->paginate(20);
        }elseif($typeid==3){//Viator商品
            if (isset($post['keywords']) and !empty($post['keywords'])) {
                $info_where['g.goods_name'] = ['like', '%' . $post['keywords'] . '%'];
            }

            $info = db("goods g")
                ->join("(".$query.") as q","g.goods_id=q.groupid")
                ->where($info_where)
                ->field("g.goods_id as id,g.goods_name as name,q.counts")
                ->paginate(20);
        }elseif($typeid==4) {//供应商
            //供应商
            $KbxOther = new KbxOther();
            $supplierArr = $KbxOther->kbx_suppliers_list();

            $faq = db("faq")
                ->where("typeid",4)
                ->where("deleted",0)
                ->field("count(id) as counts,groupid")
                ->group("groupid")
                ->select();

            $faqArr = [];
            foreach ($faq as $k_f=>$v_f) {
                $faqArr[$v_f['groupid']] = $v_f['counts'];
            }

            $kbx_url = config('kbx_url');

            if (isset($post['keywords']) and !empty($post['keywords'])) {
                $keywords = $post['keywords'];
                foreach ($supplierArr as $k=>$v) {
                    if(false==strstr($v['name'],$keywords)){
                        continue;
                    }
                    $info[$k]['id'] = $v['id'];
                    $info[$k]['name'] = $v['name'];
                    $info[$k]['url'] = $kbx_url."/admin/supplier/".$v['id'];
                    $info[$k]['counts'] = isset($faqArr[$v['id']]) ? $faqArr[$v['id']] : 0;
                }
            }else{
                foreach ($supplierArr as $k=>$v) {
                    $info[$k]['id'] = $v['id'];
                    $info[$k]['name'] = $v['name'];
                    $info[$k]['url'] = $kbx_url."/admin/supplier/".$v['id'];
                    $info[$k]['counts'] = isset($faqArr[$v['id']]) ? $faqArr[$v['id']] : 0;
                }
            }
        }elseif($typeid==5) {//城市
            $faq = db("faq")
                ->where("typeid",5)
                ->where("deleted",0)
                ->field("count(id) as counts,groupid")
                ->group("groupid")
                ->select();
            $faqArr = [];
            foreach ($faq as $k_f=>$v_f) {
                $faqArr[$v_f['groupid']] = $v_f['counts'];
            }

            $city_where = [];
            if (isset($post['keywords']) and !empty($post['keywords'])) {
                $city_where['name'] = ['like', '%' . $post['keywords'] . '%'];
            }

            $cityArr = db("city")
                ->where("type","CITY")
                ->where("deleted","0")
                ->where($city_where)
                ->field("id,name")
                ->select();

            foreach ($cityArr as $k=>$v) {
                $info[$k]['id'] = $v['id'];
                $info[$k]['name'] = $v['name'];
                $info[$k]['counts'] = isset($faqArr[$v['id']]) ? $faqArr[$v['id']] : 0;
            }
        }elseif($typeid==6 || $typeid==7 || $typeid==8 || $typeid==9) {//6销售话术  7新人培训   8定制行程方案  9产品开发需求
            $faq = db("faq")
                ->where("typeid",$typeid)
                ->where("deleted",0)
                ->field("count(id) as counts,groupid")
                ->group("groupid")
                ->select();
            $faqArr = [];
            foreach ($faq as $k_f=>$v_f) {
                $faqArr[$v_f['groupid']] = $v_f['counts'];
            }

            if (isset($post['keywords']) and !empty($post['keywords'])) {
                $info_where['f.title'] = ['like', '%' . $post['keywords'] . '%'];
            }

            $info_where['f.typeid'] = $typeid;
            $info_where['f.deleted'] = 0;
            $faqtitle = db("faqtitle")
                ->alias("f")
                ->join("admin a","f.creater=a.id","left")
                ->where($info_where)
                ->field("f.id,f.title as name,a.nickname as creater")
                ->order("id desc")
                ->select();

            $info = [];
            foreach ($faqtitle as $k=>$v) {
                $info[$k]['id'] = $v['id'];
                $info[$k]['name'] = $v['name'];
                $info[$k]['creater'] = !empty($v['creater']) ? $v['creater'] : '';
                $info[$k]['counts'] = isset($faqArr[$v['id']]) ? $faqArr[$v['id']] : 0;
            }
        }

        $this->assign('typeid', $typeid);
        $this->assign('info', $info);
        $this->assign('wherelist', $post);
        return $this->fetch();
    }

    //FAQ页
    public function showFaq(){
        $typeid = $this->request->has('typeid') ? $this->request->param('typeid', 0, 'intval') : 0;
        if($typeid <= 0){
            return $this->error('typeid不正确');
        }

        if($typeid==4){//供应商ID为mongoid，字符串格式
            $groupid = $this->request->has('groupid') ? $this->request->param('groupid') : '';
            if($groupid==''){
                return $this->error('groupid不正确');
            }
        }else{
            $groupid = $this->request->has('groupid') ? $this->request->param('groupid', 0, 'intval') : 0;
            if($groupid<=0){
                return $this->error('groupid不正确');
            }
        }

        $where = [];
        $where['groupid'] = $groupid;
        $where['typeid'] = $typeid;
        $where['deleted'] = 0;

        $faq = db('faq')->where($where)->select();
        if(!empty($faq)) {
            foreach ($faq as $k=>$v) {
                $create_user = explode('-',$v['create_user']);
                $update_user = explode('-',$v['update_user']);
                if(!empty($create_user[1]) && $create_user[1]=='supplier'){
                    $admin1 = (new CommonApi())->getSupplierAdminInfo($create_user[0]);
                    $admin1['nickname'] = $admin1['supplier_name']??'';
                }else{
                    $admin1 = db("admin")->where("id",$v['create_user'])->field("nickname")->find();
                }

                if(!empty($update_user[1]) && $update_user[1]=='supplier'){
                    $admin2 = (new CommonApi())->getSupplierAdminInfo($update_user[0]);
                    $admin2['nickname'] = $admin2['supplier_name']??'';
                }else{
                    $admin2 = db("admin")->where("id",$v['update_user'])->field("nickname")->find();
                }
                $faq[$k]['createtime'] = date("Y-m-d H:i",$v['createtime']);
                $faq[$k]['updatetime'] = !empty($v['updatetime']) ? date("Y-m-d H:i",$v['updatetime']) : '';
                $faq[$k]['create_user'] = !empty($admin1['nickname']) ? $admin1['nickname'] : '';
                $faq[$k]['update_user'] = !empty($admin2['nickname']) ? $admin2['nickname'] : '';

                $imgArr = [];
                if(!empty($v['img'])){
                    $imgArr = explode(",",$v['img']);
                    $imgArr = array_filter($imgArr);
                }

                $faq[$k]['img'] = $imgArr;
            }
        }

        $name = '';
        if($typeid==1){//产品
            $data = db("product")->where("id",$groupid)->field("name")->find();
            $name = $data['name'];
        }elseif($typeid==2){//POI

        }elseif($typeid==3){//Viator商品
            $data = db("goods")->where("goods_id",$groupid)->field("goods_name")->find();
            $name = $data['goods_name'];
        }elseif($typeid==4){//供应商
            $KbxOther = new KbxOther();
            $supplierArr = $KbxOther->kbx_suppliers_list();
            foreach ($supplierArr as $k=>$v) {
                if($v['id']==$groupid){
                    $name = $v['name'];
                    break;
                }
            }
        }elseif($typeid==5){//城市
            $data = db("city")->where("id",$groupid)->field("name")->find();
            $name = $data['name'];
        }elseif($typeid==6 || $typeid==7 || $typeid==8 || $typeid==9){//6销售话术  7新人培训  8定制行程方案   产品开发需求
            $data = db("faqtitle")->where("id",$groupid)->field("title as name")->find();
            $name = $data['name'];
        }

        $this->assign('name',$name);
        $this->assign('typeid',$typeid);
        $this->assign('groupid',$groupid);
        $this->assign('faq',$faq);
        return $this->fetch();
    }

    //新增FAQ
    public function addFaq(){
        $post = request()->post();
        if(!isset($post['typeid']) || !isset($post['groupid'])){
            return json(['code'=>-1,'msg'=>'缺少参数']);
        }

        $adminid = Cookie::get('admin');

        $addArr = [];
        $addArr['typeid'] = $post['typeid'];
        $addArr['groupid'] = $post['groupid'];
        $addArr['title'] = $post['title'];
        $addArr['content'] = $post['content'];
        $addArr['create_user'] = $adminid;
        $addArr['createtime'] = time();

        $faqModel = new faqModel();
        if(false == $faqModel->allowField(true)->save($addArr)) {
            return $this->error('添加失败');
        } else {
            return $this->success('添加成功');
        }
    }

    //编辑FAQ
    public function modify(){
        $post = request()->post();
        if(!isset($post['faq_id'])){
            return json(['code'=>-1,'msg'=>'缺少faq_id参数']);
        }
        $faq_id = $post['faq_id'];
        $adminid = Cookie::get('admin');

        $updateArr = [];
        $updateArr['title'] = $post['title'];
        $updateArr['content'] = $post['content'];
        $updateArr['update_user'] = $adminid;
        $updateArr['updatetime'] = time();

        $admin = db("admin")->where("id",$adminid)->field("nickname")->find();
        $resData = ['update_user'=>$admin['nickname'],'updatetime'=>date("Y-m-d H:i",$updateArr['updatetime'])];

        if(false == Db::name('faq')->where('id',$faq_id)->update($updateArr)) {
            return $this->error('修改失败');
        } else {
            return $this->success('修改成功','',$resData);
        }
    }

    //删除FAQ
    public function delFaq(){
        $post = request()->post();
        if(!isset($post['faq_id'])){
            return json(['code'=>-1,'msg'=>'缺少faq_id参数']);
        }
        $faq_id = $post['faq_id'];
        $adminid = Cookie::get('admin');

        $updateArr = [];
        $updateArr['deleted'] = 1;
        $updateArr['update_user'] = $adminid;
        $updateArr['updatetime'] = time();

        if(false == Db::name('faq')->where('id',$faq_id)->update($updateArr)) {
            return $this->error('删除失败');
        } else {
            return $this->success('删除成功');
        }
    }


    //新增FAQ的title
    public function addTitle(){
        $post = request()->post();
        $typeid = !empty($post['typeid']) ? $post['typeid'] : '';
        $title = !empty($post['title']) ? $post['title'] : '';
        $data['typeid'] = $typeid;
        $data['title'] = $title;

        $adminid = Cookie::get('admin');
        $data['creater'] = $adminid;


        $faqtitleModel = new faqtitleModel();
        if(false == $faqtitleModel->allowField(true)->save($data)) {
            return $this->error('添加失败');
        } else {
            return $this->success('添加成功');
        }
    }






    //抓取旧FAQ脚本
    public function getFaqOld(){
        $map['faq'] = ['neq','null'];
        $data = db("product")->where($map)->field("id,faq")->select();

        echo "<pre>";
        var_dump($data);
        echo "</pre>";

        foreach ($data as $k=>$v) {
            $addArr = [];
            $addArr['typeid'] = 1;
            $addArr['groupid'] = $v['id'];
            $addArr['title'] = '';
            $addArr['content'] = $v['faq'];
            $addArr['create_user'] = 37;
            $addArr['createtime'] = time();

            $faqModel = new faqModel();
            if(false == $faqModel->allowField(true)->save($addArr)) {
                echo $v['id']."添加失败";
                echo "<br>";
            } else {
                echo $v['id']."添加成功";
                echo "<br>";
            }
        }

        exit;
    }



}
